package com.ics.cmsadmin.modules.pub.service;

import com.ics.cmsadmin.modules.pub.dao.StudentMapper;
import com.ics.cmsadmin.frame.core.exception.CmsException;
import com.ics.cmsadmin.modules.pub.bean.Student;
import com.ics.cmsadmin.frame.utils.KeyUtil;
import lombok.extern.log4j.Log4j2;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Log4j2
public class StudentService extends ResourceService<StudentMapper, Student, String> {
    @Autowired
    StudentMapper studentMapper;

    @Autowired
    private WeChatAuthService weChatAuthService;


    public Student findOneByOpenId(String openId) {
        if (StringUtils.isBlank(openId)) {
            return null;
        }
        return studentMapper.findOneByOpenId(openId);
    }

    public Student findOneByUnionId(String unionId) {
        if (StringUtils.isBlank(unionId)) {
            return null;
        }
        return studentMapper.findOneByUnionId(unionId);
    }

    public Student addStudent(String access_token, String openId) throws CmsException {
        JSONObject userInfo = weChatAuthService.getUserInfo(access_token, openId);
        log.info("userInfo:{}",userInfo);
        Student student = new Student();
        student.setId(KeyUtil.genUniqueKey());
        student.setOpenId(userInfo.getString("openid"));
        student.setUnionId(userInfo.getString("unionid"));
        student.setNickname(userInfo.getString("nickname"));
        student.setAvatar(userInfo.getString("headimgurl"));
        student.setGender(userInfo.getString("sex"));
        student.setIsActive(Boolean.TRUE);
        studentMapper.insert(student);
        student = findOneByOpenId(openId);
        return student;
    }

    public Student findOne(String openId, String unionId) {
        return studentMapper.findOne(openId,unionId);
    }
}
